package cn.itcast.bos.web.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.dao.utils.PinYin4jUtils;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.PageBean;
import cn.itcast.bos.service.AreaService;
import cn.itcast.bos.service.CourierService;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;



@Controller
@Namespace("/")
@ParentPackage("json-default")
@Scope("prototype")
public class AreaAction extends BaseAction<Area>{

	/*private Area area = new Area();
	@Override
	public Area getModel() {
		return area;
	}*/
	
	@Autowired
	private AreaService areaService;
	
	
	// 文件上传的定义三个变量，但是我们这里只是拿到文件后对文件进行解析，而不是复制，故只需一个file属性即可
	private File file; // java.io包下的
	public void setFile(File file) {
		this.file = file;
	}

	// 批量区域导入
	@Action(value="area_batchImport")
	public String batchimport() throws FileNotFoundException, IOException{
		
		
		// 解析 Excel 逻辑  
		// 工作薄 --- sheet --- row --- cell  

		// 基于.xls格式解析HSSF
		
		List<Area> areas = new ArrayList<Area>();
		// 1、加载EXCLE对象
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
		// 2、读取一个sheet
		HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
		// 3、读取sheet中的每一行
		for(Row row :sheet){
			
			if(row.getRowNum() == 0){
				// 跳过第一行
				continue;
			}
			
			if(row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).getStringCellValue())){
				continue;
			}
			
			Area area = new Area();
			area.setId(row.getCell(0).getStringCellValue());
			area.setProvince(row.getCell(1).getStringCellValue());
			area.setCity(row.getCell(2).getStringCellValue());
			area.setDistrict(row.getCell(3).getStringCellValue());
			area.setPostcode(row.getCell(4).getStringCellValue());
			
			// 基于pinyin4j生成城市编码和简码
			String province = area.getProvince();
			String city = area.getCity();
			String district = area.getDistrict();
			
			// 将省、市、区这几个的最后的一个字去掉
			province = province.substring(0, province.length()-1);
			city = city.substring(0, city.length()-1);
			district = district.substring(0,district.length()-1);
			
			// 简码:得到得是所有的省+市+区域的一个数组，每个元素是省+市+区域
			String[] headArray = PinYin4jUtils.getHeadByString(province + city + district);
			
			StringBuffer stringBuffer = new StringBuffer();
			
			for(String headStr : headArray){
				stringBuffer.append(headStr);
			}
			// 将得到的字段信息添加到area中
			String shortCode = stringBuffer.toString();
			area.setShortcode(shortCode);
			
			// 城市编码
			String citycode = PinYin4jUtils.hanziToPinyin(city, "");
			area.setCitycode(citycode);
			
			areas.add(area);
			
			// 添加依赖
			// 导入工具类
			
		}
		
		areaService.saveBatch(areas);
		// 调用业务层
		
		System.out.println(file);
		
		return NONE;
	}


	// 有条件分页查询区域信息
	@Action(value="area_Query",results={@Result(name="success",type="json")})
	public String query(){
		
		// dao层的findAll方法必须的参数pageable，Specification
		
		Pageable pageable = new PageRequest(page -1 ,rows);
		
		Specification<Area> specification = new Specification<Area>() {

			
			List<Predicate> list = new ArrayList<Predicate>();
			@Override
			public Predicate toPredicate(Root<Area> root,
					CriteriaQuery<?> query, CriteriaBuilder cb) {
				// 已经将area注入到root里了
				// province like ?
				if(StringUtils.isNotBlank(model.getProvince())){
					Predicate p1 = cb.like(root.get("province").as(String.class),"%"+model.getProvince()+"%");
					list.add(p1);
				}
				if(StringUtils.isNotBlank(model.getCity())){
					Predicate p2 = cb.like(root.get("city").as(String.class),"%"+model.getCity()+"%");
					list.add(p2);
				}
				if(StringUtils.isNotBlank(model.getDistrict())){
					Predicate p3 = cb.like(root.get("district").as(String.class), "%"+model.getDistrict()+"%");
					list.add(p3);
				}
				
				return cb.and(list.toArray(new Predicate[0]));
			}
		};
		
		// 调用service层方法
		Page<Area> page= areaService.findAll(specification,pageable);
		pushPageDataToValueStack(page);
		
		return SUCCESS;
		
	}

	/*private void PageRequest(int i, int rows2) {
		
	}
	*/
	

}
